package org.hcf.common.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author repack
 */
public class TimeUtils {
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_YYYYMMDD = "yyyy/MM/dd";
    public static final String DATE_FORMAT_YYYYMMDD2 = "yyyy年MM月dd日";
    public static final String DATE_FORMAT_YMD = "yyyy-MM-dd";
    public static final String DATE_FORMAT_YMDHM = "yyyyMMddHHmm";
    public static final String DATE_FORMAT_YMDHMS = "yyyyMMddHHmmss";
    public static final String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
    public static final String DATE_YEAR_MONTH_DAY = "yyyy年MM月dd日";
    public static final String DATE_FORMAT_YYYYMM = "yyyy年MM月";
    public static final String UTC_DATE = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    static ZoneOffset defaultOffset = ZoneOffset.of("+8");

    /**
     * LocalDateTime转 时间戳 单位秒
     *
     * @param time
     * @return
     */
    public static long toSecond(LocalDateTime time) {
        return time.toEpochSecond(defaultOffset);
    }

    /**
     * LocalDateTime转时间戳 单位毫秒
     *
     * @param time
     * @return
     */
    public static long toMill(LocalDateTime time) {
        return time.toInstant(defaultOffset).toEpochMilli();
    }

    public static LocalDateTime now() {
        return LocalDateTime.now();
    }

    public static long getNowMill() {
        return now().toInstant(defaultOffset).toEpochMilli();
    }

    public static LocalDateTime toTime(long time) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(time), defaultOffset);
    }

    /**
     * LocalDateTime转 String   格式:yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static String toStr(LocalDateTime time) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
        return time.atOffset(defaultOffset).format(formatter);
    }

    /**
     * Stringe转 LocalDateTim 格式:yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static LocalDateTime toTime(String time) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_FORMAT);
        return LocalDateTime.parse(time, df).atOffset(defaultOffset).toLocalDateTime();
    }

    /**
     * date转LocalDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime toTime(Date date) {
        return date.toInstant().atZone(defaultOffset).toLocalDateTime();
    }

    /**
     * LocalDateTime转date
     *
     * @param localDateTime
     * @return
     */
    public static Date toDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(defaultOffset).toInstant());
    }

}
